#include "buffer.h"
#include <cstdarg> // ellipsis (aka ...)

/* @implement */
unsigned int VAO, VBO, EBO;

/* @implement */
// vertex buffer objects
void initVBO(float *vertices, int sizeofVertices)
{
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeofVertices, vertices, GL_STATIC_DRAW);
}

/* @implement */
// vertex array objects
// @params count, size1, size2, ...
void initVAO(int count, ...)
{
	va_list list;
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);

    // 求各参数之和
	int sum = 0;
	va_start(list, count);
	for (int i = 0; i < count; ++i) {
		sum += va_arg(list, int);
    }
	va_end(list);

    int offset = 0;
	va_start(list, count);
    for (int i = 0; i < count; ++i) {
        int size = va_arg(list, int);
        glVertexAttribPointer(
            i,
            size,
            GL_FLOAT, // type
            GL_FALSE, // normalized
            sum * sizeof(float), // stride
            (void*)(offset * sizeof(float)) // begin pointer
        );
        glEnableVertexAttribArray(i);
        offset += size;
    }
    va_end(list);
}

// element buffer objects (call this after binding VAO)
void initEBO(unsigned int *indices, int sizeofIndices)
{
    glGenBuffers(1, &EBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeofIndices, indices, GL_STATIC_DRAW);
    //glBindVertexArray(0); // unbound VAO, can be left out
}
